package com.jeect.userservice3.config;

import com.jeect.userservice3.filter.ApiUsernamePasswordAuthenticationProcessingFilter;
import com.jeect.userservice3.service.impl.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class WebAuthenticationConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthenticationService authenticationService;

    @Autowired
    private AuthticationFailureHandler authticationFailureHandler;
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private AuthLogoutSuccessHandler authLogoutSuccessHandler;
    static String[] ALLOW_URLS = {
            "/user/page/",
            "/user/login",
            "/user/loginout/"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ApiUsernamePasswordAuthenticationProcessingFilter apiUsernamePasswordAuthenticationProcessingFilter =
                new ApiUsernamePasswordAuthenticationProcessingFilter();
        apiUsernamePasswordAuthenticationProcessingFilter.setAuthenticationManager(super.authenticationManagerBean());
        apiUsernamePasswordAuthenticationProcessingFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        apiUsernamePasswordAuthenticationProcessingFilter.setAuthenticationFailureHandler(authticationFailureHandler);

        http.csrf().disable()
                //.addFilterBefore(apiUsernamePasswordAuthenticationProcessingFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterAt(apiUsernamePasswordAuthenticationProcessingFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests().antMatchers(ALLOW_URLS).permitAll()
                .and()
                .formLogin().loginProcessingUrl("/user/login")
//                .successHandler(authenticationSuccessHandler)
//                .failureHandler(authticationFailureHandler);
                .and().logout().logoutUrl("/user/logout")
                .logoutSuccessHandler(authLogoutSuccessHandler)
                .clearAuthentication(true).invalidateHttpSession(true);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authenticationService).passwordEncoder(new BCryptPasswordEncoder());
    }


}
